package com.gt.xmall.util;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jmesa.facade.TableFacade;
import org.jmesa.limit.Limit;
import org.jmesa.limit.SortSet;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;

import com.google.common.collect.Lists;
import com.gt.xmall.model.GtdProject;

public class PagerUtil  {
	/**
	 * 初始化搜索过滤器
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, SearchBean> initSearchFilters(
			ServletRequest request) {
		// Map<String, SearchBean> filters = Maps.newHashMap();
		Map<String, Object> searchParams = ServletUtil
				.getParametersStartingWith(request, "search_");
		return SearchBean.parse(searchParams);
	}

	public static <T> Specification<T> getSpecification(ServletRequest request,final Class<T> clazz) {
		Map<String, Object> searchParams = ServletUtil
				.getParametersStartingWith(request, "search_");

		Specification<T> spec = DynamicSpecifications.bySearchFilter(
				(SearchBean.parse(searchParams)).values(),clazz);
		return spec;
	}

	 

	public PageRequest initPageRequest(String tableId,
			HttpServletRequest request, HttpServletResponse response,
			int totalRows ) {

		TableFacade tableFacade = new TableFacade(tableId, request, response);
		tableFacade.setTotalRows(totalRows);
		
		
		Limit limit = tableFacade.getLimit();
		SortSet sortSet = limit.getSortSet();
		// Collection<org.jmesa.limit.Sort> sorts=sortSet.getSorts();
		List<org.springframework.data.domain.Sort.Order> _orders = Lists
				.newArrayList();
		for (org.jmesa.limit.Sort sort : sortSet.getSorts()) {
			_orders.add(new org.springframework.data.domain.Sort.Order(
					Direction.fromString(sort.getOrder().toParam()), sort
							.getProperty()));
		}
		
		// limit.getRowSelect().getPage();
		// limit.getRowSelect().getMaxRows();
		return new PageRequest(limit.getRowSelect().getPage() - 1, tableFacade.getMaxRows(),
				new org.springframework.data.domain.Sort(_orders));
	}
}
